#!/usr/bin/python
# coding:utf-8
__author__ = 'good'
__createday__ = '2015-01-15'

import datetime

import flask

from flask import json

import golsee
from golsee import models


def visit_json():
    today = datetime.datetime.now().date()
    visits = dict()
    labels = list()
    visit = list()
    attack = list()
    robot = list()
    real = list()
    redata = models.Blog_info.query.order_by(models.Blog_info.date.desc()).limit(15)
    for d in redata:
        visit.append(str(d.visit_day))
        attack.append(str(d.visit_attack_day))
        labels.append(str(d.date)[5:])
        robot.append(str(d.visit_robot_day))
        real.append(str(d.visit_day - d.visit_attack_day - d.visit_robot_day))
    labels.reverse()
    attack.reverse()
    visit.reverse()
    robot.reverse()
    real.reverse()
    for i in range(20 - len(visit)):
        de = datetime.timedelta(days=i + 1)
        labels.append(str(today + de)[5:])
    visits['labels'] = labels
    visits['visit'] = visit
    visits['attack'] = attack
    visits['robot'] = robot
    visits['real'] = real
    return json.dumps(visits)


def article_json():
    article = dict()
    art = models.Article.count_by_category()
    labels = list()
    datas = list()
    for a in art:
        labels.append(a.name)
        d = {
            'value': a.count,
            'name': a.name
        }
        datas.append(d)
    article['labels'] = labels
    article['datas'] = datas
    return json.dumps(article)


@golsee.cache.memoize(unless=True, timeout=60)
def calendar_json():
    arg = flask.request.args
    start, stop = arg['start'], arg['end']
    create_article = models.Article.query.filter(models.Article.post_date >= start).filter(
        models.Article.post_date <= stop).all()
    update_article = models.Article.find_edit(start, stop)
    visit = models.Blog_info.query.all()
    data = []
    for a in create_article:
        dic = {
            'title': u'新增文章' + a.title,
            'url': '/article_show/' + a.title,
            'start': str(a.post_date)
        }
        data.append(dic)
    for a in update_article:
        dic = {
            'title': u'更新文章' + a.title,
            'url': '/' + a.title,
            'start': str(a.timestamp)
        }
        data.append(dic)
    for v in visit:
        dic = {
            'title': u'日访问量:' + str(v.visit_day),
            'start': str(v.date)
        }
        data.append(dic)
    print data
    return json.dumps(data)
